﻿// <copyright file="SquareExtension.cs" company="Ecole Normale Supérieure">
// Released under GPLv2
// </copyright>
// <summary>Contains the class SquareExtension</summary>

namespace Sqwarea.GameLogic.Extensions
{
    using Sqwarea.GameLogic.Exceptions;
    using Sqwarea.Persistence;

    /// <summary>
    /// Provides square extensions for the connexity algorithm
    /// </summary>
    public static class SquareExtension
    {
        /// <summary>
        /// Tell whether the next element of the PathToKing going from s1 is s2
        /// </summary>
        /// <param name="s1">The square whose PathToKing is looked at</param>
        /// <param name="s2">The other square</param>
        /// <returns>True iff the next element of the PathToKing going from s1 is s2</returns>
        public static bool PointsTo(this Square s1, Square s2)
        {
            switch (s1.PathToKing)
            {
                case Direction.North:
                    return s1.Position.GetNorth() == s2.Position;

                case Direction.East:
                    return s1.Position.GetEast() == s2.Position;

                case Direction.South:
                    return s1.Position.GetSouth() == s2.Position;

                case Direction.West:
                    return s1.Position.GetWest() == s2.Position;

                default:
                    return false;
            }
        }

        /// <summary>
        /// If s1 and s2 are adjacent, make s1 points to s2
        /// Else throw a exception
        /// </summary>
        /// <param name="s1">The square whose PathToKing is modified</param>
        /// <param name="s2">The other square</param>
        public static void MakePointsTo(this Square s1, Square s2)
        {
            if (s2.Position == s1.Position.GetNorth())
            {
                s1.PathToKing = Direction.North;
            }
            else if (s2.Position == s1.Position.GetEast())
            {
                s1.PathToKing = Direction.East;
            }
            else if (s2.Position == s1.Position.GetSouth())
            {
                s1.PathToKing = Direction.South;
            }
            else if (s2.Position == s1.Position.GetWest())
            {
                s1.PathToKing = Direction.West;
            }
            else
            {
                throw new ConnexityLogicException("SquareExtension.MakePointsTo : not adjacent squares");
            }
        }
    }
}